#coding=utf8
from google.appengine.ext import db
import datetime

def str2date(s):
    '''2002-04-09 --> date type'''
    return datetime.date( *map(int, s.split('-')) )
    
class Stock(db.Model):
    code = db.StringProperty(required=True)
    
    name = db.StringProperty()
    market = db.StringProperty()
    
    ipo = db.DateProperty()
    iprice = db.FloatProperty()
    
    created_at = db.DateProperty(auto_now_add=True)
    
    def update_tss(self, tss):
        '''tss: 像 [['2002-07-10', '653655400'],...,['2002-04-09', '600000000']]的数据'''
        for ts in tss:
            t = self.tss.filter('value =', int(ts[1])).fetch(1)
            if t:continue
            else:
                t = TradableShare()
                t.s = self
                t.value = int(ts[1])
                t.since = str2date(ts[0])
                t.put()
    
    def get_current_ts(self): 
        return self.tss.order('-since').fetch(1)[0].value
    ts = property(get_current_ts)
                       
class TradableShare(db.Model):
    s = db.ReferenceProperty(Stock, collection_name='tss')

    value = db.IntegerProperty()
    since = db.DateProperty()

    created_at = db.DateProperty(auto_now_add=True)
        
def create_stock(stock_data):
    '''stock_data: stockcrawler.get_stock的返回值'''
    
    code = stock_data['code']
    s = Stock(code=code, key_name='stock_%s'%code)
    
    s.name = unicode( stock_data['name'], 'u8')
    s.market = stock_data['market']
    s.ipo = str2date( stock_data['ipo'] )
    s.iprice = float( stock_data['iprice'] )
    
    s.put()
    
    return s
   
